/**
 * JSparrow - Une version numérique du jeu "Attention Pirates !" - Copyright (C) 2014 Black Pearl
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program. If
 * not, see <http://www.gnu.org/licenses/>.
 */
package App.Vue;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;

import App.Controleur.Jeu;

@SuppressWarnings("serial")
public class Panneau_Reparer extends JPanel_Principal {

	private String[] emplacements;
	private ButtonGroup[] radioGroup;
	private JRadioButton[] pirates;
	private JRadioButton[] canons;
	private int credits;
	private JLabel labelCredits;
	protected Jeu controleur;
	private Panneau_Jeu panneauJeu;
	//Utile pour peindre l'arriere plan
	private Image parchemin;
	private boolean flagInit = true;
	/**
	 * Créer un nouveau panneau réparer
	 * @param pieces Tableau de String[6] contenant la dispo des pieces {"pirate","canon","",coffre2"...}
	 * @param credits
	 */
	public Panneau_Reparer(Jeu controleur, Panneau_Jeu panneauJeu, String[] pieces, int credits){

		this.controleur = controleur;
		//Redimensionne le panneau
		this.panneauJeu = panneauJeu;
		Dimension ecran = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
		Rectangle screenBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
		int SCRX =(int)(screenBounds.width*0.18); 
		int SCRY = (int)(screenBounds.height*0.26);
		this.setPreferredSize(new Dimension(SCRX,SCRY));

		this.setBorder(new EmptyBorder(10, 0, 40, 70) );

		this.emplacements = pieces;
		this.credits = credits;
		radioGroup = new ButtonGroup[6];
		pirates = new JRadioButton[6];
		canons  = new JRadioButton[6];
		this.initPanel();
		this.etatEmplacement(this.emplacements);

	}

	/**
	 * Détermine l'etat des boutons radios
	 */
	private void etatEmplacement(String[] pieces){

		int i;

		for(i=0;i<6;i++){
			switch(pieces[i]){
			case "1" :
				pirates[i].setSelected(true);
				canons[i].setSelected(false);
				break;
			case "2" :
				pirates[i].setSelected(false);
				canons[i].setSelected(true);
				break;
			case "0" :
				radioGroup[i].clearSelection();
				break;
			default :	
				pirates[i].setEnabled(false);
				canons[i].setEnabled(false);
			}
		}

	}


	/**
	 * Dispose les éléments du panneau Reparer
	 */
	private void initPanel(){

		int i;
		//Initialisation layout
		this.setLayout(new GridBagLayout());
		//Transparence du panneau
		this.setBackground(TRANSPARENT);
		this.setOpaque(false);

		JLabel[] labelEmplacement = new JLabel[6];
		JLabel reparer = new JLabel("Réparer");
		labelCredits = new JLabel("Crédits : " + credits + " ");
		//Font et couleur des titres
		reparer.setFont(titreFont);
		labelCredits.setFont(titreFont);
		reparer.setForeground(Color.BLACK);
		labelCredits.setForeground(Color.BLACK);

		//Création des boutons
		JButton valider = new JButton("Valider");
		JButton retour = new JButton("Retour");
		JButton annuler = new JButton("Réinitialiser");

		//Font et couleur des bouton
		valider.setFont(boutonFont);
		retour.setFont(boutonFont);
		annuler.setFont(boutonFont);
		valider.setForeground(Color.BLACK);
		retour.setForeground(Color.BLACK);
		annuler.setForeground(Color.BLACK);

		//ajout des listener
		valider.addActionListener(new boutonListener(valider.getText()));
		retour.addActionListener(new boutonListener(retour.getText()));
		annuler.addActionListener(new boutonListener("Annuler"));


		for(i=0;i<6;i++){

			//Initialisation des boutons radios
			pirates[i] = new JRadioButton("Pirate");
			pirates[i].addActionListener(new radioListener(i,"pirate"));
			canons[i] = new JRadioButton("Canon");
			canons[i].addActionListener(new radioListener(i,"canon"));
			radioGroup[i] = new ButtonGroup();
			radioGroup[i].add(pirates[i]);
			radioGroup[i].add(canons[i]);
			labelEmplacement[i] = new JLabel("Emplacement " + (i+1) + " : ");

			//TRansparence des fonds
			pirates[i].setBackground(TRANSPARENT);
			canons[i].setBackground(TRANSPARENT);
			pirates[i].setOpaque(false);
			canons[i].setOpaque(false);

			//Font et couleur
			pirates[i].setFont(texteFont);
			canons[i].setFont(texteFont);
			labelEmplacement[i].setFont(texteFont);
			pirates[i].setForeground(Color.BLACK);
			canons[i].setForeground(Color.BLACK);
			labelEmplacement[i].setForeground(Color.BLACK);
		}



		//Ajout titres
		addItem(reparer, 0, 0, 1, 1, GridBagConstraints.FIRST_LINE_START);
		addItem(labelCredits, 5, 0, 1, 1, GridBagConstraints.FIRST_LINE_END);

		//Emplacement 1
		addItem(labelEmplacement[0], 0, 1, 1, 1, GridBagConstraints.WEST);
		addItem(canons[0], 1, 1, 1, 1, GridBagConstraints.WEST);
		addItem(pirates[0], 2, 1, 1, 1, GridBagConstraints.WEST);

		//Emplacement 2
		addItem(labelEmplacement[1], 0, 2, 1, 1, GridBagConstraints.WEST);
		addItem(canons[1], 1, 2, 1, 1, GridBagConstraints.WEST);
		addItem(pirates[1], 2, 2, 1, 1, GridBagConstraints.WEST);

		//Emplacement 3
		addItem(labelEmplacement[2], 0, 3, 1, 1, GridBagConstraints.WEST);
		addItem(canons[2], 1, 3, 1, 1, GridBagConstraints.WEST);
		addItem(pirates[2], 2, 3, 1, 1, GridBagConstraints.WEST);

		//Emplacement 4
		addItem(labelEmplacement[3], 3, 1, 1, 1, GridBagConstraints.WEST);
		addItem(canons[3], 4, 1, 1, 1, GridBagConstraints.WEST);
		addItem(pirates[3], 5, 1, 1, 1, GridBagConstraints.WEST);

		//Emplacement 5
		addItem(labelEmplacement[4], 3, 2, 1, 1, GridBagConstraints.WEST);
		addItem(canons[4], 4, 2, 1, 1, GridBagConstraints.WEST);
		addItem(pirates[4], 5, 2, 1, 1, GridBagConstraints.WEST);

		//Emplacement 6
		addItem(labelEmplacement[5], 3, 3, 1, 1, GridBagConstraints.WEST);
		addItem(canons[5], 4, 3, 1, 1, GridBagConstraints.WEST);
		addItem(pirates[5], 5, 3, 1, 1, GridBagConstraints.WEST);

		//Boutons
		addItem(valider, 4, 4, 1, 1, GridBagConstraints.EAST);
		addItem(retour, 5, 4, 1, 1, GridBagConstraints.WEST);
		addItem(annuler, 0, 4, 1, 1, GridBagConstraints.WEST);
	}


	/**
	 * Ajoute un composant au panel
	 * @param c Composant à ajouter
	 * @param x No de colonne
	 * @param y No de ligne
	 * @param width Nb de cases horyzontales à prendre
	 * @param height Nb de cases verticales à prendre
	 * @param align Contrainte d'alignement dans la case
	 */
	private void addItem(JComponent c, int x, int y, int width, int height, int align) {
		GridBagConstraints gc = new GridBagConstraints();
		gc.gridx = x;
		gc.gridy = y;
		gc.gridwidth = width;
		gc.gridheight = height;
		gc.weightx = 0;
		gc.weighty =0;
		gc.insets = new Insets(5, 5, 5, 5);
		gc.anchor = align;
		gc.fill = GridBagConstraints.NONE;
		this.add(c, gc);
	}



	/**
	 * Listener des boutons radio
	 */
	class radioListener implements ActionListener{

		private int emplacement,i,difference;
		private String type;

		public radioListener(int emplacement,String type){
			super();
			this.emplacement = emplacement;
			this.type = type;
		}

		/**
		 * Gere le nombre de credits restant a chaque choix
		 */
		@Override
		public void actionPerformed(ActionEvent e) {
			int difference = 0;
			
			System.out.println("NB credit : " + credits);
			for(i=0;i<6;i++){
				if(canons[i].isEnabled()){//si l'emplacement n'est pas pris par un coffre
					if((emplacementToString(i).equals("2")) && !(emplacements[i].equals("2"))){
						difference++;
					}
				}
				if(pirates[i].isEnabled()){//si l'emplacement n'est pas pris par un coffre
					if((emplacementToString(i).equals("1")) && !(emplacements[i].equals("1"))){
						difference++;
					}
				}
			}


			System.out.println("NB dif : " + difference);
			
			if(difference > credits){//Si il y a eu plus de modification que de cr�dits, on efface le choix precedent
				if(emplacements[emplacement].equals("0")){
					radioGroup[emplacement].clearSelection();

				}
				else{
					if(type.equals("canon") ){
						pirates[emplacement].setSelected(true);
					}
					else{
						canons[emplacement].setSelected(true);
					}
				}
				labelCredits.setText("Crédits : 0 ");
			}
			else{
				labelCredits.setText("Crédits : " + (credits-difference) + " ");
			}

		}

	}


	/**
	 * Listener des boutons
	 */
	class boutonListener implements ActionListener{

		String bouton;
		public boutonListener(String bouton){
			super();
			this.bouton = bouton;
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			//TODO : Notification au controleur
			switch (bouton) {
			case "Annuler" ://Reinitialise la disposition
				etatEmplacement(emplacements);
				labelCredits.setText("Crédits : " + credits + " ");
				break;
			case "Valider":
				panneauJeu.validerClicReparer();
				controleur.gestionEvenementVue(reparer());
				break;
			case "Retour" :
				panneauJeu.retourClicReparer();
				break;
			default :
			}
		}

	}

	/**
	 * Peint l'arrière plan
	 */
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		if(flagInit){
			try {
				BufferedImage bufferedFond = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("img/parcheminH.png"));
				parchemin = bufferedFond.getScaledInstance(this.getWidth(),this.getHeight(), 0);

			} catch (IOException e) {
				e.printStackTrace();
			}
			flagInit = false;
		}
		g.drawImage(parchemin, 0, 0, this);
	}

	/**
	 * Met à jour le panneau réparer
	 * @param pieces Tableau de String[6] contenant la dispo des piece {"pirate","canon","",coffre2"...}
	 * @param credits
	 */
	public void updateReparer(String[] pieces,int credits){
		this.emplacements = pieces;
		System.out.println(pieces[0]);
		System.out.println(pieces[1]);

		System.out.println(pieces[2]);
		this.credits = credits;
		etatEmplacement(pieces);
		labelCredits.setText("Crédits : " + credits + " ");
	}

	private String reparer(){	
		return "reparer="+emplacementToString(0)+"-"+emplacementToString(1)+"-"+emplacementToString(2)+"-"+emplacementToString(3)+"-"+emplacementToString(4)+"-"+emplacementToString(5);
	}

	private String emplacementToString(int emplacement){

		if(pirates[emplacement].isEnabled()){
			if(pirates[emplacement].isSelected()){
				return "1"; //Pirate
			}
			else if (canons[emplacement].isSelected()){
				return "2"; //Canon
			}
			else{
				return "0";
			}
			
		}
		else{
			return "3";	//Coffre
		}
	}

	
}
